#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2, cookielib
import re
import string
import time

from ssi import ssi
from tcpconn import *
from packet_seq import sequencer
import cmd_processor as Processors
from logger import log, fytionException

class session(object):

    Domain = "fetion.com.cn"
    FetionVer = "4.1.1160"
    SIPCVer = "SIP-C/4.0"
    
    def __init__(self, fytion):
        # 0: init, 1: begin reg, 2: fin sub
        self._state = 0
        self._fytion = fytion
        self._sysconf = fytion._sysconf
        self._myconf = fytion._myconf
    
    def login(self, conf):
        self._conn = tcpconn(conf['proxy'])
        self._seq = sequencer(self, self._conn)
        self._seq.background_tick()
        
        log("Registering new session...")
        self._register = Processors.register(self, self._seq)
        self._register.reg_session(conf['credential'])
        self._state = 1
        self.peer_uri = conf['from_uri']
        if conf.has_key('to_uri'):
            self._to_uri = conf['to_uri']
        else:
            self._to_uri = ''
    
    def send_msg(self, msgbody): 
        m = Processors.message_send(self, self._seq)
        m.send(msgbody)

    def register_fin(self):
        if self._to_uri:
            self.invite(self._to_uri)
        else:
            self._state = 2
    
    def invite(self, uri):
        i = Processors.invite(self, self._seq)
        i.invite(uri)
    
    def invite_fin(self):
        self._state = 2
        self.peer_uri = self._to_uri
        self._to_uri = ''
    
    def keepbusy_seq(self, seq):
        s = Processors.keepbusy(self, seq)
        s.keepbusy()
    
    def seq_conn_closed(self, e):
        self._fytion.remove_session(self)
    
    def get_message(self, data):
        self._fytion.get_message(data)
        
    def exit(self):
        b = Processors.bye(self, self._seq)
        b.bye()
        